import Vue from 'vue'
import VueRouter from 'vue-router'

// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import utils from "@/utils/index"
import store from '@/store/index'
import util from '@/libs/util.js'

import { Loading } from 'element-ui'

// axios
import axios from '@/plugin/axios'
// 路由数据
import routes from './routes'
import menuHeader from '@/menu/header'
import menuAside from '@/menu/aside'
import { frameInRoutes } from '@/router/routes'



let menuArr = require("@/utils/side.json")

// fix vue-router NavigationDuplicated
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return VueRouterPush.call(this, location).catch(err => err)
}
const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
  return VueRouterReplace.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

// 导出路由 在 main.js 里使用
const router = new VueRouter({
  routes
})

// 权限菜单处理


let permission = {
  functions: [],
  roles: [],
  isAdmin: false
};
let loading;

const getfunction = async () => {
  loading = Loading.service({
    lock: true,
    text: '数据加载中……',
    background: 'rgba(0, 0, 0, 0.7)',
    target: '.d2-theme-container-aside',
  });
  axios.get("/common/getUserInfo").then(async res => {
    localStorage.setItem('userId',res.data.user.userId)
    console.log('用户信息123', res.data.user.userId,res.data)
   
    await store.dispatch('d2admin/user/set', {
      name: res.data.user.userName
    }, { root: true })


    let permissionMenu = [];
    let menus = [
      0,
      ...res.data.menus
    ];
    console.log('开始循环', menus, menuArr.length)
    //遍历寻找用户拥有的权限
    for (let index = 0; index < menuArr.length; index++) {
      let element = menuArr[index];
      if (menus.indexOf(element.id) != -1) {
        let obj = {}
        obj = {
          ...element,
          children: []
        }
        for (let j = 0; j < element.children.length; j++) {
          const children = element.children[j];
          if (menus.indexOf(children.id) != -1) {
            obj.children.push(children)
          }
        }
        permissionMenu.push(obj)
      }
    }

    console.log('结果权限', permissionMenu)

    loading.close();

  
    let allMenuAside = [...menuAside, ...permissionMenu]
    // 处理路由 得到每一级的路由设置
    store.commit('d2admin/page/init', frameInRoutes)
    // 设置顶栏菜单
    store.commit('d2admin/menu/headerSet', menuHeader)
    // 设置侧边栏菜单
    store.commit('d2admin/menu/asideSet', allMenuAside)
    // 初始化菜单搜索功能
    store.commit('d2admin/search/init', allMenuAside)
    // 设置权限信息
    // store.commit('d2admin/permission/set', permission)
    // 加载上次退出时的多页列表
    store.dispatch('d2admin/page/openedLoad')
    await Promise.resolve()
  }).catch(() => {
    loading.close();
  });
}

//标记是否已经拉取权限信息
let isFetchPermissionInfo = false;
let fetchPermissionInfo = async () => {
  //处理动态添加的路由
  const formatRoutes = function (routes) {
    routes.forEach(route => {
      route.component = routerMapComponents[route.component]
      if (route.children) {
        formatRoutes(route.children)
      }
    })
  }
  try {
    console.log('拉去权限请求--')
    await getfunction()
    await Promise.resolve()
  } catch (ex) {
    console.log(ex)
  }
}

let getLinkToken = async () => {
  // 判断链接是否带有token
  let tokenLink = utils.modules.getQuery('token');
  let name = utils.modules.getQuery('name');
  let uuid = utils.modules.getQuery('uuid');
  if (tokenLink) {
    util.cookies.set('token', tokenLink);
  }
  if (name) {
    util.cookies.set('name', name);
  }
  if (uuid) {
    util.cookies.set('uuid', uuid);
  }
}

//免校验token白名单
let whiteList = ['/login']






//








/**
 * 路由拦截
 * 权限验证
 */
router.beforeEach(async (to, from, next) => {
  await getLinkToken();
  // 确认已经加载多标签页数据 https://github.com/d2-projects/d2-admin/issues/201
  await store.dispatch('d2admin/page/isLoaded')
  // 确认已经加载组件尺寸设置 https://github.com/d2-projects/d2-admin/issues/198
  await store.dispatch('d2admin/size/isLoaded')
  // 进度条
  NProgress.start()
  // 关闭搜索面板
  store.commit('d2admin/search/set', false)
  // 验证当前路由所有的匹配中是否需要有登录验证的
  if (to.matched.some(r => r.meta.auth)) {
    // 这里暂时将cookie里是否存有token作为验证是否登录的条件
    // 请根据自身业务需要修改
    const token = util.cookies.get('token')
    if (token && token !== 'undefined') {
      //拉取权限信息
      if (!isFetchPermissionInfo) {
        console.log('拉去权限信息')
        await fetchPermissionInfo();
        isFetchPermissionInfo = true;
        next(to.path, true)
      } else {
        next()
      }
    } else {
      // 没有登录的时候跳转到登录界面
      // 携带上登陆成功之后需要跳转的页面完整路径
      next({
        name: 'login',
        query: {
          redirect: to.fullPath
        }
      })
      // https://github.com/d2-projects/d2-admin/issues/138
      NProgress.done()
    }
  } else {
    // 不需要身份校验 直接通过
    next()
  }
})

router.afterEach(to => {
  // 进度条
  NProgress.done()
  // 多页控制 打开新的页面
  store.dispatch('d2admin/page/open', to)
  // 更改标题
  util.title(to.meta.title)
})

export default router
